<template>
  <div class="app_content">
    <el-card class="ve_container">
      <h1>管理员登录</h1>
      <el-form ref="loginForm" :model="form" :rules="state.formRule" class="ve_form" :inline="false" @keyup.enter="onSubmit">
        <el-form-item prop="username">
          <el-input v-model.trim="form.username" placeholder="账户">
            <template #prepend><i style="font-size:20px;" class="el-icon-user"></i></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model.trim="form.password" show-password placeholder="密码">
            <template #prepend><i style="font-size:20px;" class="el-icon-key"></i></template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="ve_submit" type="primary" @click="onSubmit">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { useRouter } from 'vue-router'
import { reactive, getCurrentInstance, ref } from 'vue'
import { AdminLogin } from '@/api/index.js'
import axios from 'axios'

export default {
  setup() {
    const loginForm = ref()
    const router = useRouter()
    const { proxy } = getCurrentInstance()
    const state = reactive({
      formRule: {
        username: [
          { required: true, message: '请填写用户名', trigger: 'blur' },
        ],
        password: [{ required: true, message: '请填写密码', trigger: 'blur' }],
      },
    })

    const form = reactive({
      username: 'admin',
      password: '123456',
    })

    // 提交表单
    const onSubmit = async () => {
      await loginForm.value.validate((valid) => {
        if (!valid) {
          proxy.$message.warning('请输入有效信息')
          return
        }

        AdminLogin({
          username: form.username,
          password: form.password,
        }).then((res) => {
          if (res.code == 200) {
            proxy.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
            })

            proxy.storage.setLocal('17003334_user', form.username)
            proxy.$store.commit('loginMut', 'admin')

            setTimeout(async () => {
              router.push('/admin')
            }, 1000)
          } else {
            proxy.$message.error(res.msg)
          }
        })
      })
    }

    return {
      form,
      onSubmit,
      state,
      loginForm,
    }
  },
}
</script>

<style lang="scss" scoped>
.ve_container {
  position: absolute;
  width: 400px;
  top: 50%;
  left: 50%;
  transform: translateY(-50%) translateX(-50%);
  text-align: center;
  h1 {
    font-size: 24px;
    transition: all 1s;
    font-weight: bold;
    margin-bottom: 36px;
  }
  .ve_form {
    .ve_submit {
      width: 100%;
    }

    :deep(.el-input-group__prepend) {
      padding: 0 10px;
    }
  }
}
</style>
